<?php

namespace addons\formdesign\library;

/**
 * 工具类
 */
class Formsafe
{
    public static function safe_gpc()
    {
        //$getfilter="'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
        $getfilter = "\\b(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
        $postfilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
        $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
        //安全检测 start
        if (!empty($_GET)) {
            foreach ($_GET as $key => $value) {
                self::StopAttack($key, $value, $getfilter);
            }
        }
        /* post 提交，有很多检测过度，暂停止 post */
        if (!empty($_POST)) {
            foreach ($_POST as $key => $value) {
                self::StopAttack($key, $value, $postfilter);
            }
        }

        if (!empty($_COOKIE)) {
            foreach ($_COOKIE as $key => $value) {
                self::StopAttack($key, $value, $cookiefilter);
            }
        }
        //安全检测 end
    }

    /* 安全过滤 */
    protected static function StopAttack($StrFiltKey, $StrFiltValue, $ArrFiltReq)
    {

        if (is_array($StrFiltValue)) {
            if (count($StrFiltValue) == count($StrFiltValue, 1)) {
                $StrFiltValue = implode($StrFiltValue);
            } else {
                foreach($StrFiltValue as $val){
                    $StrFiltValue = implode($val);
                    self::StopAttack($StrFiltKey, $StrFiltValue, $ArrFiltReq);
                }
                return;
            }
        }
        if (preg_match("/" . $ArrFiltReq . "/is", $StrFiltValue) == 1) {
            //slog("<br><br>操作IP: ".$_SERVER["REMOTE_ADDR"]."<br>操作时间: ".strftime("%Y-%m-%d %H:%M:%S")."<br>操作页面:".$_SERVER["PHP_SELF"]."<br>提交方式: ".$_SERVER["REQUEST_METHOD"]."<br>提交参数: ".$StrFiltKey."<br>提交数据: ".$StrFiltValue);
            //$this->error('操作被拦截，已记录，如有问题请联系管理员');

            if (IS_AJAX) { //获取
                $data = array(
                    'error' => '特殊字条被拦截',
                    'hasError' => 1,
                );
                echo "<pre>";
                print_r($data);
                echo "<pre>";
            } else {
                echo '操作被拦截，已记录，如有问题请联系管理员';
            }
            exit();
        }
    }

}
